<template>
  <div id="riliBOX">
    <el-calendar v-model="value" id="calendar">
      <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
      <template slot="dateCell" slot-scope="{date, data}">
        <!--自定义内容-->
        <div class="fkss" @click="dianji(data,date)">
          <div class="calendar-day">
            {{ data.day.split('-').slice(2).join('-') }}
            <div>
              <span v-for="(item,index) in calendarData" :key="index">
                <span class="is-selected" v-if="item.workDay==data.day">{{item.staff.name}}</span>
              </span>
            </div>
          </div>
        </div>
      </template>
    </el-calendar>
    <!-- 弹框 -->
    <el-dialog title="选择上班员工" :visible.sync="dialogFormVisible" v-if="dialogFormVisible">
      <el-form :model="mitaiform">
        <el-form-item label="日期" :label-width="formLabelWidth">
          <el-input v-model="mitaiform.workDay" autocomplete="off" disabled></el-input>
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="bettwen">
        <el-col :span="15">
          <!-- 表单 -->
          <el-form :model="tempForm" ref="tempForms">
            <el-form-item label="请选择人员">
              <!-- 多选人员 -->
              <el-checkbox-group v-model="tempForm.checkboxGroup5" size="small">
                <el-checkbox
                  border
                  v-for="(item,index) in checkBox"
                  @change="perChange(item)"
                  :label="item.id"
                  :key="index"
                  :checked="torf(item.id)"
                >{{item.name}}</el-checkbox>
              </el-checkbox-group>
              <!-- 多选人员 end-->
            </el-form-item>
          </el-form>
          <!-- 表单 end-->
          <!-- tag展示区 -->
          <el-row>
            <el-tag
              class="tagClass"
              v-for="(tag,index) in tags"
              :key="index"
              closable
              @close="handleClose(tag)"
            >{{tag.name}}</el-tag>
            <el-button v-if="tags.length>0" @click="clearAll" plain>全部删除</el-button>
          </el-row>
          <!-- tag展示区 end-->
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addpbdata()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { mapActions } from "vuex";
export default {
  name: "calendar",
  data() {
    return {
      formLabelWidth: "120px",
      dialogFormVisible: false,
      // arrangeform: [],
      mitaiform: {},
      value: new Date(),
      tags: [],
      tempForm: {
        checkboxGroup5: [] //选择的人员的ID
      },
      detailData: [{}],
      shangbanNum: [{ id: undefined }],
      torf(num) {
        for (let i = 0; i < this.shangbanNum.length; i++) {
          if (num == this.shangbanNum[i].staffId) {
            return true;
            // console.log("得到了ture");
          }
        }
      }
    };
  },
  computed: {
    calendarData() {
      let arr = [...this.$store.state.bsStore.arrangeData];
      let arr2 = [];
      // console.log(arr);

      return arr;
    },
    checkBox() {
      return this.$store.state.bsStore.Staff;
    }
  },
  methods: {
    ...mapActions([
      "getArrangeData",
      "getStaff",
      "setscheduling",
      "xiugaischeduling"
    ]),
    dianji(data, date) {
      this.clearAll();
      this.dialogFormVisible = true;
      //查询点击日期上班的员工
      this.shangbanNum = [];
      for (let i = 0; i < this.calendarData.length; i++) {
        if (this.calendarData[i].workDay == data.day) {
          this.shangbanNum.push(this.calendarData[i]);
        } else {
          this.shangbanNum.push({});
        }
      }

      this.mitaiform.workDay = data.day;
    },
    //全部清除tag
    clearAll() {
      this.tags = [];
      this.tempForm.checkboxGroup5 = [];
    },
    perChange(item) {
      // console.log('我执行了perChange');
      this.detailData.push(item);
    },
    handleClose(tag) {
      //标签的删除事件
      // 去掉当前删除的tag
      let yourChoseTags = this.tempForm.checkboxGroup5;
      this.tempForm.checkboxGroup5 = yourChoseTags.filter(item => {
        if (tag.id !== item) {
          return true;
        }
      });
    },
    //数组对象去重
    delRepeat(arr) {
      // console.log('delRepeat');
      return Object.values(
        arr.reduce((obj, next) => {
          var key = JSON.stringify(next);
          return (obj[key] = next), obj;
        }, {})
      );
    },
    moreArr() {
      // console.log('MOREARR');
      //把选中的tag的ID赋值给yourchose
      let yourChose = this.tempForm.checkboxGroup5;
      let tempTags = [];
      //定义一个变量，将查询到选中tag对应的所有员工信息返回给detailData
      tempTags = this.baseDataDetail(yourChose, this.checkBox, tempTags);
      this.detailData = tempTags;
      // console.log( this.detailData);
    },
    //处理函数（选中的tag的集合 ， 所有的员工，需要返回的空数组）
    baseDataDetail(yourChose, baseData, callBack) {
      // console.log('baseDataDetail');
      //封装的数组方法
      let temp = callBack;
      // 循环两个数据拿到选择的checkbox的id对应的初始数据
      yourChose.forEach(item => {
        baseData.forEach(itemSecond => {
          if (item === itemSecond.id) {
            temp.push(itemSecond);
          }
        });
      });
      return temp;
    },
    addpbdata() {
      this.dialogFormVisible = false
      let xiugaibef = [];
      this.shangbanNum.forEach(item => {
        item.id !== undefined ? xiugaibef.push(item) : "";
      });
        console.log(xiugaibef);
        
      if (this.tags && xiugaibef) {
        //将修改前的日期全部删除
        let xiugaiqian = [];
        // 调整传给后台的格式并循环调用接口
        for (let i = 0; i < xiugaibef.length; i++) {
          let obj1 = {};
          obj1.workDay = this.mitaiform.workDay;
          obj1.timeSlot = 0;
          this.checkBox.forEach(item => {
            if (xiugaibef[i].staffId == item.id) {
              obj1.id = item.id;
            }
          });
          xiugaiqian.push(obj1);
        }
        //执行删除上班员工
        for (let i = 0; i < xiugaiqian.length; i++) {
          this.xiugaischeduling(xiugaiqian[i]);
        }

        //执行添加员工的
        let arr = [];
        //调整传给后台的格式并循环调用接口
        for (let i = 0; i < this.tags.length; i++) {
          let obj = {};
          obj.workDay = this.mitaiform.workDay;
          obj.timeSlot = 0;
          this.checkBox.forEach(item => {
            if (this.tags[i].id == item.id) {
              obj.staffId = item.id;
            }
          });
          arr.push(obj);
        }
        for (let i = 0; i < arr.length; i++) {
          this.setscheduling(arr[i]).then(res=>{
            if(res===200){
               this.getArrangeData()
            }
          })
        }
       
        
      }
    }
  },
  watch: {
    //监听到把选中TAG所有的员工信息赋值给detailData后
    detailData() {
      // console.log('detailData');
      //合并对象并去重后赋值给Tags 渲染在页面上
      let tempArr = Object.assign([], this.detailData);
      tempArr = this.delRepeat(tempArr);
      this.tags = tempArr;
      // console.log('执行完毕');

      // console.log(this.tags);
      // console.log(this.tempForm);
    },
    //监听点击tag之后 调用 this.moreArr
    "tempForm.checkboxGroup5"() {
      console.log("tempForm.checkboxGroup5");
      this.moreArr();
    }
  },
  created() {
    this.getArrangeData();
    this.getStaff();
  }
};
</script>


<style scoped>
.calendar-day {
  text-align: center;
  color: #202535;
  font-size: 12px;
}
.is-selected {
  color: #f8a535;
  font-size: 10px;
  margin-top: 5px;
}
#calendar
  .el-button-group
  > .el-button:not(:first-child):not(:last-child):after {
  content: "当月";
}
#calendar {
  line-height: 100%;
}
.fkss {
  width: 100%;
  height: 100%;
}
</style>
